<template>
  <div class="landing">
    <div class="landing-content">
      <h1>{{ app?.name || '应用' }}</h1>
      <p>正在为您打开应用或跳转到自定义发行地址...</p>
      <el-button type="primary" @click="start">立即打开</el-button>
    </div>
  </div>
</template>

<script>
import { appDetailApi } from '@/api/apps';

export default {
  data() {
    return {
      id: '',
      app: null,
    }
  },
  async created() {
    this.id = this.$route.params.id
    const res = await appDetailApi(this.id)
    if (res && res.code === 200) {
      this.app = res.data
      this.start()
    }
  },
  methods: {
    async recordVisit() {
      try {
        // 生成设备指纹
        const fingerprint = window.XappTool ? await new window.XappTool().generateDeviceFingerprint() : 'unknown';
        
        // 收集访问信息
        const trackData = {
          tracking_id: 'track_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
          appkey: this.app?.appkey || '',
          fingerprint: fingerprint,
          session_id: sessionStorage.getItem('session_id') || (sessionStorage.session_id = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)),
          device_info: {
            userAgent: navigator.userAgent,
            platform: navigator.platform,
            language: navigator.language,
            screenResolution: `${screen.width}x${screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            referrer: document.referrer
          },
          custom_params: this.$route.query || {}
        };

        // 上报访问记录
        await fetch('/api/landing/track', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(trackData)
        });
      } catch (error) {
        console.warn('访问记录上报失败:', error);
      }
    },
    
    async start() {
      if (!window.XappTool) return
      
      // 先记录访问
      await this.recordVisit();
      
      const sdk = new window.XappTool()
      sdk.init({ app_key: this.app.appkey }).then(() => {
        sdk.autoJump({
          ios: { store: this.app.appstore_down_url },
          android: { store: this.app.googleplay_down_url },
          harmony: { store: this.app.huawei_down_url },
          fallback: this.app.custom_distribution_url,
          params: this.$route.query || {},
          preferFallback: true
        })
      })
    }
  }
}
</script>

<style scoped>
.landing {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.landing-content { text-align: center; }
</style>